use html_editor::operation::*;
use html_editor::{
    operation::{Queryable, Selector},
    parse, Element, Node,
};
use serde_json::Value;
use tracing::{debug, Level};

#[tokio::test]
async fn run() {
    tracing_subscriber::fmt()
        .with_max_level(Level::DEBUG)
        .init();

    let movie_name = "猪猪侠之超星五灵侠第5季";

    let movie_url = "https://nnyy.best/movie/308070";

    let resp = reqwest::get(movie_url).await.unwrap();

    let headers = resp.headers();

    let body_bytes = resp.bytes().await.unwrap();
    let body_str = String::from_utf8_lossy(&body_bytes);

    // debug!("{}", body_str);

    let document = parse(&body_str).unwrap();

    // debug!("[document]:{:?}", document);
    let selector: Selector = Selector::from("script");

    let elements = document.query_all(&selector);

    let script = elements
        .iter()
        .filter(|ele| ele.attrs.len() == 0)
        .take(1)
        .next()
        .unwrap();
    let script_str = script.html();

    let s_tag = "var movie = {";
    let e_tag = "};";

    let s_index = script_str.find(s_tag).unwrap();
    let e_index = script_str.find(e_tag).unwrap();

    let json_str = &script_str[(s_index + s_tag.len() - 1)..(e_index + e_tag.len() - 1)];

    let json_obj = serde_json::from_str::<Value>(json_str).unwrap();

    let src_list = json_obj.get("play_lines").unwrap();

    let src_list = src_list.as_array().unwrap();

    for src in src_list {
        let name = src.get("name").map(|s| s.as_str()).flatten().unwrap_or("");
        println!("=====  {name}  =====");
        let p_list = src
            .get("data")
            .map(|v| v.as_array().cloned())
            .flatten()
            .unwrap_or(Vec::<_>::new());

        for p in p_list {
            let name = p.get("name").map(|s| s.as_str()).flatten().unwrap_or("");
            let url = p.get("url").map(|s| s.as_str()).flatten().unwrap_or("");
            println!("m3u8_dl '{name}' '{url}' ");
        }
    }
}
